package com.tbynet.jwp.admin.post;

import java.math.BigInteger;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import com.jfinal.aop.Inject;
import com.jfinal.kit.Ret;
import com.jfinal.kit.StrKit;
import com.jfinal.plugin.activerecord.Page;
import com.tbynet.jwp.admin.AdminController;
import com.tbynet.jwp.framework.kit.DateKit;
import com.tbynet.jwp.framework.kit.JsoupKit;
import com.tbynet.jwp.framework.kit.StringKit;
import com.tbynet.jwp.model.Options;
import com.tbynet.jwp.model.Postmeta;
import com.tbynet.jwp.model.Posts;
import com.tbynet.jwp.model.TermTaxonomy;
import com.tbynet.jwp.service.CommentService;
import com.tbynet.jwp.service.OptionService;
import com.tbynet.jwp.service.PostService;
import com.tbynet.jwp.service.TermService;
import com.tbynet.jwp.service.UserService;

public class PostAdminController extends AdminController {
	
	@Inject
	PostService postService;
	
	@Inject
	TermService termService;
	
	@Inject
	UserService userService;
	
	@Inject
	CommentService commentService;
	
	@Inject
	OptionService optionService;

	public void index() {
		set("all", postService.count(null));
		set("publish", postService.count(Posts.POST_STATUS_PUBLISH));
		set("sticky", 0);
		set("draft", postService.count(Posts.POST_STATUS_DRAFT));
		set("pending", postService.count(Posts.POST_STATUS_PENDING));
		set("trash", postService.count(Posts.POST_STATUS_TRASH));
		
		render("index.html");
	}
	
	public void search() throws Exception {
		String status = getPara("status");
		String q = getPara("q");
		
		Page<Posts> page = postService.search(getPage(), getSize(), Posts.POST_TYPE_POST, status, q);
		for(Posts post : page.getList()) {
			post.put("sticky", optionService.getOption(Options.sticky_posts).hasStickyPosts(post.getID().intValue()));
			post.put("categories", termService.getTerms(post.getID(), TermTaxonomy.TAXONOMY_CATEGORY));
			post.put("tags", termService.getTerms(post.getID(), TermTaxonomy.TAXONOMY_POST_TAG));
			post.put("author", userService.getUser(post.getPostAuthor()));
			post.put("comments", commentService.count(post.getID()));
			post.put("post_modified_format", DateKit.format(post.getPostModified(), "yyyy-MM-dd"));
		}
		
		ok(Ret.by("data", page));
	}
	
	public void create() {
		set("date", new Date(System.currentTimeMillis()));
		set("categories", termService.getParents(TermTaxonomy.TAXONOMY_CATEGORY));
		render("create.html");
	}
	
	public void edit() {
		Posts post = postService.getPost(getPara("post"), Posts.POST_TYPE_POST);
		
		set("post", post);
		set("categories", termService.getParents(TermTaxonomy.TAXONOMY_CATEGORY));
		render("edit.html");
	}
	
	public void save() throws Exception {
		String postType = Posts.POST_TYPE_POST;//文章类型		
		String postTitle = getPara("post_title");//文章标题，必填
		String postName = getPara("post_name", StringKit.urlencode(postTitle));// (slug) 文章别名
		String postContent = getPara("post_content");//文章内容，必填
		String postStatus = getPara("post_status");//新文章的状态
		String postPassword = getPara("post_password");//文章浏览密码
		String postAuthor = getPara("post_author");//作者编号
		String postDate = getPara("post_date");//文章编辑日期
		String postDateGmt = getPara("post_date_gmt", postDate);//文章编辑GMT日期
		String postExcerpt = getPara("post_excerpt", StringKit.substring(JsoupKit.getText(postContent), 240));//摘要信息
		String postParent = getPara("post_parent", "0");//新文章的父文章编号
		
		int menuOrder = getParaToInt("menu_order", 0);//如果新文章是页面，设置显示顺序
		String commentStatus = getPara("comment_status", "open");// 评论的状态
		String pingStatus = getPara("ping_status", "open");// ping的状态
		String pinged = getPara("pinged", "");//该文章被ping到的地址
		String toPing = getPara("to_ping", "");//该文章需要ping到的地址

		String _thumbnailId = getPara("_thumbnail_id");

		String format = getPara("post_format", "0");//文章形式
		
		String[] categories = getParaValues("category");//分类
		
		List<String> tags = new ArrayList<String>();//标签
		
		String taxTag = getPara("tax_tag");
		if(StrKit.notBlank(taxTag)) {
			for(String tag : taxTag.split("、")) {
				if(StrKit.notBlank(tag)) {
					tags.add(tag);
				}
			}
		}
		String newTag = getPara("new_tag");
		if(StrKit.notBlank(newTag)) {
			for(String tag : newTag.split("、")) {
				if(StrKit.notBlank(tag)) {
					tags.add(tag);
				}
			}
		}
		
		boolean sticky = getParaToBoolean("sticky", false);//将文章置于首页顶端
		
		Posts post = new Posts();
		post.setPostTitle(postTitle);
		post.setPostName(postName);
		post.setPostContent(postContent);
		post.setPostStatus(postStatus);
		post.setPostType(postType);
		post.setPostPassword(postPassword);
		post.setPostAuthor(new BigInteger(postAuthor));
		post.setPostDate(DateKit.toDate(postDate));
		post.setPostDateGmt(DateKit.toDate(postDateGmt));
		post.setPostModified(new Date(System.currentTimeMillis()));
		post.setPostModifiedGmt(new Date(System.currentTimeMillis()));
		post.setPostExcerpt(postExcerpt);
		post.setPostParent(new BigInteger(postParent));
		post.setPostContentFiltered("");
		post.setMenuOrder(menuOrder);
		post.setCommentStatus(commentStatus);
		post.setPingStatus(pingStatus);
		post.setPinged(pinged);
		post.setToPing(toPing);
		
		List<Postmeta> postmetas = new ArrayList<Postmeta>();
		
		Postmeta editLock = new Postmeta();
		editLock.setMetaKey(Postmeta._edit_lock);
		editLock.setMetaValue(new Date().getTime() + ":" + 1);
		postmetas.add(editLock);
		
		Postmeta editLast = new Postmeta();
		editLast.setMetaKey(Postmeta._edit_last);
		editLast.setMetaValue("1");
		postmetas.add(editLast);
		
		Postmeta thumbnailId = new Postmeta();
		thumbnailId.setThumbnailId(_thumbnailId);
		postmetas.add(thumbnailId);
		
		if(postService.save(post, postmetas, format, categories, tags.toArray(new String[tags.size()]), sticky)) {
			ok(Ret.by("msg", "撰写新文章成功").set("data", post.getID()));
		} else {
			fail("撰写新文章失败，请联系管理员");
		}
	}
	
	public void update() {
		
	}
	
	public void trash() {
		Posts post = postService.getPost(getPara("post"));
		post.setPostStatus(Posts.POST_STATUS_TRASH);
		
		if(post.update()) {
			ok(Ret.by("msg", "移到回收站成功").set("data", post.getID()));
		} else {
			fail("移到回收站失败，请联系管理员");
		}
	}
	
}
